<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="preview"
      :on-remove="remove"
      :on-change="change"
      :http-request="uploadHttpRequest"
      :before-upload="uploadBefore"
      :limit="limitNum"
      :class="{displayed: fileListLength}"
    >
      <i v-if="show" class="el-icon-plus" />
      <i v-else class="el-icon-picture-outline" />
    </el-upload>
    <el-progress v-if="showPercent" :percentage="percent" style="width:197px" />
    <el-dialog :visible.sync="showDialog" title="图片预览" width="50%">
      <img :src="imgSrc" alt="" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKID7GF1aw3wb3HwNaaMtBG9oFSQTIsGUVIs',
  SecretKey: 'TikYBZieMr79xWv51jDSTHEwRilaAVeY'
})
export default {
  name: 'ImageUpload',
  props: {
    show: {
      type: Boolean,
      default: true
    },
    limitNum: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgSrc: null,
      uid: null,
      percent: 0,
      showPercent: false
    }
  },
  computed: {
    // 判断图片文件列表的数量是否大于0，通过这个来控制上传图标的显示
    fileListLength() {
      return this.fileList.length >= 1 && this.show
    }
  },
  methods: {
    // 预览文件
    preview(file) {
      this.showDialog = true
      this.imgSrc = file.url
    },
    // 删除文件
    remove(file, fileList) {
      this.fileList = fileList
    },
    // 文件状态发生改变时的钩子函数
    change(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    // 文件上传前的钩子函数，对文件进行相关的判断(类型和大小)
    uploadBefore(file) {
      const type = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png', 'image/webp']
      if (!type.includes(file.type)) {
        this.$message.warning('文件上传的格式错误,请重新上传！')
        return Promise.reject('文件上传格式错误')
      }
      // 文件大小要小于5M
      const maxLength = 10 * 1024 * 1024
      if (maxLength < file.size) {
        this.$message.warning('文件上传的大小不能超过5M,请重新上传')
        return Promise.reject('文件上传的大小过大')
      }
      // 记录当前上传成功的图片的uid，便于上传到腾讯云之后将这个uid对象的图片文件地址替换成线上的地址
      this.uid = file.uid
      this.showPercent = true
      return true
    },
    // 上传操作，自定义上传
    uploadHttpRequest(params) {
      cos.putObject({
        Bucket: 'renliziyuan-1316172230',
        Region: 'ap-guangzhou',
        Key: params.file.name,
        Body: params.file,
        StorageClass: 'STANDARD', // 上传的模式类型
        onProgress: (progressData) => {
          this.percent = parseInt(progressData.percent * 100)
        }
      },
      (err, data) => {
        if (!err && data.statusCode === 200) {
          this.fileList = this.fileList.map(item => {
            if (item.uid === this.uid) {
              return { url: 'http://' + data.Location, upload: true }
            }
            return item
          })
          /* this.fileList.forEach(item => {
            if (item.uid === this.uid) {
              item.url = 'http://' + data.Location
              item.upload = true
            }
          }) */
          setTimeout(() => {
            this.showPercent = false
            this.percent = 0
          }, 1000)
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .displayed{
  .el-upload--picture-card {
    display: none;
  }
  /* .el-upload-list--picture-card {
    .el-upload-list__item-status-label{
      display: block;
    }
  } */
}
</style>
